from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render
from django.core.paginator import Paginator
from PIL import Image
import time,os
from datetime import datetime

from myapp.models import Picinfo

def index(request):
    '''浏览列表'''
    list = Picinfo.objects.all()

    pIndex = 1
    p = Paginator(list,3)
    list2 = p.page(pIndex)
    plist = p.page_range

    if not list:
        context = {"info": "相册中没有照片，你可以点击下方添加选项添加新相片。"}
        return render(request, "myapp/info.html", context)
    else:
        context = {"plist": list2 , "pplist":plist , "pIndex":pIndex}
        return render(request, "myapp/index.html", context)

def picInfos(request, pIndex):
    '''浏览列表'''
    list = Picinfo.objects.all()

    if pIndex == '':
        pIndex = 1
    pIndex = int(pIndex)
    p = Paginator(list,3)
    list2 = p.page(pIndex)
    plist = p.page_range
    p_count = p.count
    p_num = p.num_pages

    if not list:
        context = {"info": "相册中没有照片，你可以点击下方添加选项添加新相片。"}
        return render(request, "myapp/info.html", context)
    else:
        context = {"plist": list2 , "pplist":plist , "pIndex":pIndex ,"p_count":p_count,"p_num":p_num}
        return render(request, "myapp/index.html", context)

def addPicinfos(request):
    return render(request, "myapp/add.html")

def insertPicinfos(request):
    picFile = request.FILES.get("picture", None)
    if not picFile:
        context = {"info": "没有上传相片信息！"}
        return render(request, "myapp/info.html", context)
    else:
        filename = str(time.time()) + "." + picFile.name.split('.').pop()
        destination = open("./static/" + filename, "wb+")
        for chunk in picFile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        # 执行图片缩放
        im = Image.open("./static/" + filename)
        # 缩放到75*75(缩放后的宽高比例不变):
        im.thumbnail((100, 100))
        # 把缩放后的图像用jpeg格式保存:
        im.save("./static/pics/s_" + filename, None)

        try:
            p = Picinfo()
            p.name = filename
            p.title = request.POST['title']
            p.text = request.POST['text']
            p.size = str(im.size[0]) + "*" + str(im.size[1])
            p.time = datetime.now()
            p.save()
            context = {"info": "添加成功！"}
        except Exception as err:
            print(err)
            context = {"info": "添加失败！"}

        return render(request, "myapp/info.html", context)

def delPicinfos(request , uid):
    try:
        pi = Picinfo.objects.get(id=uid)
        pi.delete()
        context = {"info": "删除成功！"}
    except:
        context = {"info": "删除失败！"}
    return render( request , "myapp/info.html", context)


def editPicinfos(request,uid):
    pic = Picinfo.objects.get(id = uid)
    context = {'picInfo':pic}
    return render(request, "myapp/edit.html", context)

def updatePicinfos(request):
    try:
        p = Picinfo.objects.get(id=request.POST['pid'])

        fileImg = request.FILES.get("picture", None)

        if fileImg:
            '''删除原图片'''
            os.remove("./static/"+p.name)
            filename = str(time.time()) + "." + fileImg.name.split('.').pop()
            destination = open("./static/" + filename, "wb+")
            for chunk in fileImg.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()

            # 执行图片缩放
            im = Image.open("./static/" + filename)
            # 缩放到75*75(缩放后的宽高比例不变):
            im.thumbnail((100, 100))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/pics/s_" + filename, None)

            p.name = filename
            if request.POST['title']:
                p.title = request.POST['title']
            if request.POST['text']:
                p.text = request.POST['text']
            p.size = str(im.size[0]) + "*" + str(im.size[1])
            p.time = datetime.now()

            p.save()
        context = {"info":"修改成功！"}
    except Exception as err:
        print(err)
        context = {"info":"修改失败！"}
    return render(request,"myapp/info.html",context)


